package com.hzit.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.dto.StudentDTO;
import com.hzit.entity.Student;
import com.hzit.mapper.StudentMapper;
import com.hzit.service.IStudentService;
import com.hzit.util.Conver;
import com.hzit.util.PageResult;
import com.hzit.vo.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

	@Autowired
	private Conver conver;
	//1. 分页查询学生
	@Override
	public PageResult<StudentDTO> findByPage(Integer page, Integer pageSize) {
		//1.1 开始分页
		// @MapperScan("com.hzit.mapper"): 封装了分页参数
		Page<Student> studentPage = this.page(new Page<>(page, pageSize));
		//1.2 得到每页的记录集合
		List<Student> records = studentPage.getRecords();
		//1.3 将上面的List<Student> 转换为List<StudentDTO>
		List<StudentDTO> dtos = conver.entity2DTO(records);
		//1.4 直接返回PageResult
		return new PageResult<>(dtos,studentPage.getTotal());
	}

	//2. 条件查询带分页
	@Override
	public PageResult<StudentDTO> search(Integer page, Integer pageSize, StudentVo vo) {
		//2.1 开始分页
		//2.1.1 定义包装查询条件的包装器对象
		QueryWrapper<Student> wrapper = new QueryWrapper<>();
		if(vo != null){
			wrapper.like(StrUtil.isNotBlank(vo.getSname()),"sname",vo.getSname())               // 学生姓名查询
			       .like(StrUtil.isNotBlank(vo.getAddr()),"addr",vo.getAddr())                  // 学生住址
				   .eq(vo.getCid() != null && vo.getCid() !=0 ,"cid",vo.getCid());	   // 学生所在班级
		}
		Page<Student> studentPage = this.page(new Page<>(page, pageSize), wrapper);
		//2.2 得到查询的每页的记录结果集集合
		List<Student> records = studentPage.getRecords();
		//2.3 转换为List<StudentDTO>集合
		List<StudentDTO> dtos = conver.entity2DTO(records);
		//2.4 返回
		return new PageResult<>(dtos,studentPage.getTotal());
	}
}
